package Servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.ProcessBuilder.Redirect;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.JEditorPane;

import org.json.JSONException;
import org.json.JSONObject;

import DAL.Entites.Game;
import DAL.JDBC.JedisConn;

import redis.clients.jedis.Jedis;

public class AddItem extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public AddItem() {
        super();
        // TODO Auto-generated constructor stub
    }


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		JSONObject jsonObject = new JSONObject();
		HttpSession session = request.getSession();
		Jedis jedis = JedisConn.getConnection();
		
		if(session.getAttribute("uid") == null)
		{	
			//get the new uid from jedis
			jedis.incr("global:uid");
			String uid = jedis.get("global:uid");
			session.setAttribute("uid", uid);
		}
		
		String uid = session.getAttribute("uid").toString();
		String gameId = request.getParameter("gameId");
		
		jedis.sadd("carts:"+uid, gameId);
		List<String> items = new ArrayList<String>();
		for (Object item : jedis.smembers("carts:"+uid)) {
			items.add(item.toString());
		}
			
		try {
			jsonObject.put("items", items);
			jsonObject.put("uid", uid);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		PrintWriter pw = response.getWriter();
		pw.write(jsonObject.toString());
	}
}
